package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/model"
	"src/util/context"
	"src/util/log"
	"strconv"
)

var busLogger = log.GetLogger()

func writebusLoggerLoggerLog(funcName, errMsg string, err error) {
	busLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "bus.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func GetBusGps(c echo.Context) error {
	rouid, err := strconv.Atoi(c.QueryParam("routeid"))
	if err != nil {
		writebusLoggerLoggerLog("GetAllBusGps", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	busid := c.QueryParam("busid")
	data := model.GetBusByroute(rouid, busid)
	return context.RetData(c, data)
}

type busgps struct {
	Name   string  `json:"name"`
	Lat    float64 `json:"lat"`
	Lon    float64 `json:"lon"`
	Direct int     `json:"direct"`
}

func GetAllBusGps(c echo.Context) error {
	AllBusGps := []busgps{}
	tembus := busgps{}
	for i, j := range config.Busmessages.BusToId {
		tembus.Name = i
		tembus.Lat = config.Busmessages.BusMessage[j].PreGPS_GCJ02[0]
		tembus.Lon = config.Busmessages.BusMessage[j].PreGPS_GCJ02[1]
		tembus.Direct = config.Busmessages.BusMessage[j].BusDriveDir
		AllBusGps = append(AllBusGps, tembus)
	}
	return context.RetData(c, AllBusGps)
}

func ChangeRoute(c echo.Context) error {
	Change := ChangeRouteParam{}
	_ = c.Bind(&Change)
	flag := false
	for i, _ := range config.Rou.BusRoute {
		if i == Change.Name {
			flag = true
		}
	}
	if !flag {
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "无此校车")
	}
	if Change.Id >= len(config.Rou.Routes) {
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "ID越界")
	}
	config.Rou.BusRoute[Change.Name] = Change.Id
	return context.RetData(c, "success")
}
